package com.caption.auth.secuity.username;

import com.caption.auth.model.entity.SysRole;
import com.caption.auth.secuity.entity.SysUserDetails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @description: 用户名密码认证(默认方式)
 * @author: 码农
 * @date: 2021-12-31 20:04:57
 */
@Component
public class UsernameAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    private UserDetailsServiceImpl userDetailsService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String username = (String) authentication.getPrincipal();
        String password = (String) authentication.getCredentials();
        SysUserDetails userInfo = userDetailsService.loadUserByUsername(username);
        if (userInfo == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        if (!new BCryptPasswordEncoder().matches(password, userInfo.getPassword())) {
            throw new BadCredentialsException("密码不正确");
        }
        Set<GrantedAuthority> authorities = new HashSet<>();
        List<SysRole> roles = userInfo.getRoles();
        if (!CollectionUtils.isEmpty(roles)) {
            for (SysRole role : roles) {
                authorities.add(new SimpleGrantedAuthority(role.getCode()));
            }
        }
        userInfo.setAuthorities(authorities);
        // 此时鉴权成功后，应当重新 new 一个拥有鉴权的 authenticationResult 返回
        return new UsernamePasswordAuthenticationToken(userInfo, password, authorities);
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
